<?php
namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketDiy;
use addons\cloud_market\model\CloudMarketSite;
use addons\cloud_market\model\CloudMarketSiteAddonToken;

class Diy extends CloudMarketApiController
{
    protected $notApiLogin = ['*'];
    protected $notApiCheck = ['*'];
    protected $noCheck = [];

    /**
     * @var CloudMarketDiy
     */
    protected $model;

    /**
     * @var CloudMarketSite|array|\think\Model|null
     */
    private $siteMsg;

    protected $site_id;
    protected $token;
    protected $domain;
    protected $addon_token;
    protected $addon_name;

    protected function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketDiy();

        if (!in_array($this->request->action(), $this->noCheck)) {
            $this->site_id = $this->request->post('site_id');
            $this->token = $this->request->post('token');
            $this->domain = $this->request->post('domain');
            $this->addon_token = $this->request->post('addon_token', '');
            $this->addon_name = $this->request->post('addon_name', '');

            if (!$this->site_id || !$this->token) {
                return $this->error('参数错误，站点的token不正确', input());
            }

            $site = (new CloudMarketSite())->where(['id' => $this->site_id, 'token' => $this->token])->find();
            if (!$site) {
                return $this->error('没有找到当前站点，请联系售后', input());
            }

            if ($site['domain'] != $this->domain) {
                return $this->error('绑定的域名与云端域名不符合，请联系售后');
            }

            $this->siteMsg = $site;

            if (!$this->addon_token || !$this->addon_name) {
                return $this->error('参数错误，应用或者应用token为空');
            }

            $site_addon = (new CloudMarketSiteAddonToken())->where(['token' => $this->addon_token, 'addon_name' => $this->addon_name])->find();
            if (!$site_addon) {
                return $this->error('当前平台下的应用/小程序Token不正确', input());
            }

            if ($site_addon['status'] == -1) {
                return $this->error('当前平台下的此应用已被封禁，详情请联系', input());
            }
        }
    }

    /**
     * 获取DIY模板列表
     */
    public function getList()
    {
        $this->model->params['order'] = "state DESC,down_count DESC";
        $where = [
            ['page_name', '=', input('page_name', '')],
            ['addon_name', '=', input('addon_name', '')],
        ];

        $mix = [];
        if ($this->siteMsg['level'] > 0) {
            // 管理员
            $mix = [];
        } else {
            $mix['whereRaw'] = ["`state` > '0' or `site_id` = '" . $this->siteMsg['id'] . "'"];
        }

        $mix['$where'] = $where;
        $mix['field'] = ['name,page_name,cover_image,id,state,remark,site_id,down_count'];
        $res = $this->model->getPageList($mix);
        return $this->success($res['count'], $res['data']);
    }

    /**
     * 查询单个DIY模板
     */
    public function get()
    {
        $id = input('id', 0);
        $diy = $this->model->where(['id' => $id])->find();

        if ($diy) {
            return $this->success('', $diy);
        } else {
            return $this->error('获取失败', []);
        }
    }

    /**
     * 审核DIY模板
     */
    public function check()
    {
        $row = input('data', []);
        if (!$row['id']) {
            return $this->error('当前模板ID不存在');
        }
        $diy = $this->model->where(['id' => $row['id']])->find();
        if (!$diy) {
            return $this->error('当前模板不存在');
        }

        $diy->state = $row['state'] ?? -1;
        $diy->remark = $row['remark'] ?? '';
        $diy->save();

        return $this->success('审核成功！');
    }

    /**
     * 删除DIY模板
     */
    public function del()
    {
        $id = input('id', 0);
        $res = $this->model->where(['id'=>$id])->find();
        if($res){
            $res->delete();
        }
        return $this->success('删除成功');
    }

    /**
     * 下载DIY模板
     */
    public function down()
    {
        $id = input('id', 0);
        $diy = $this->model->where(['id' => $id])->find();

        if ($diy) {
            $diy->down_count = $diy->down_count + 1;
            $diy->save();
            return $this->success('ok', $diy['diy_data']);
        } else {
            return $this->error('未找到');
        }
    }

    /**
     * 新增/编辑DIY模板
     */
    public function add()
    {
        $data = request()->param(false)['data'];
        $data['addon_name'] = input('addon_name', '');
        $data['site_id'] = input('site_id', 0);
        $data['id'] = $data['id'] ?? 0;

        if (!$data['addon_name'] || !$data['site_id']) {
            return $this->error('应用名称或者站点ID不存在');
        }

        $diy = $this->model->where(['id' => $data['id']])->findOrEmpty();

        if ($diy->isEmpty()) {
            $data['user_id'] = $this->siteMsg['user_id'];
            // $count = $this->model->where(['site_id' => $data['site_id'], 'addon_name' => $data['addon_name'], 'page_name' => $data['page_name']])->count();
            // if ($count > 1 && $this->siteMsg['level'] <= 0) {
            //     return $this->error('当前站点最多上传10个模板');
            // }
            // TODO  当前站点最多上传10个模板
            $data['version'] = 1.00;
            $diy->save($data);
            return $this->success('新增成功，审核通过后会显示所有站点查看');
        } else {
            if ($diy->state != 0) {
                $diy->version = $diy->version + 0.01;
                $diy->state = 0;
            }
            $diy->save($data);
            return $this->success('编辑成功，审核通过后会显示所有站点查看');
        }
    }
}
